package yxy.game.pm2.command.mail;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PickedTroopsSlot;
import yxy.game.pm2.bean.Soul;
import yxy.game.pm2.bean.currency.CurrencyGroup;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.MailMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.mail.MailBean;
import yxy.game.pm2.module.mail.MailHandle;

import java.util.Collection;

/** 邮件 邮件领取 */
@MessageType(proto = Command.MailReceived, classtype = MailMessage.MailReceivedRequest.class)
public class CMD_MailReceived extends Command<MailMessage.MailReceivedRequest> {

	@Override
	public void execute(MessageSource messageSource, MailMessage.MailReceivedRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		MailMessage.MailReceivedResponse.Builder response = MailMessage.MailReceivedResponse.newBuilder();

		MailBean mailBean = MailBean.get(playerCode, code);
		if (mailBean == null || mailBean.expired()) {
			send(messageSource, response, Result.MailExpired);//邮件已过期
			return;
		}
		if (mailBean.isRewarded()) {
			send(messageSource, response, Result.MailRewared);//奖励已领取
			return;
		}
		if (mailBean.getRewards().size() <= 0) {
			send(messageSource, response, Result.MailNoRewared);//邮件没有奖励
			return;
		}

		Collection<Currency> rewards = mailBean.getRewards();

		//todo 判断类型是魂玉或兵符，需要再去判断是否到达上限，上限则提示并return
		for (Currency reward : rewards) {
			if ((reward.getType().getGroup().equals(CurrencyGroup.PickedTroopsSlot) && PickedTroopsSlot.all(playerCode).size() >= PickedTroopsSlot.maxNum)){
				send(messageSource, response, Result.MailNumMax);//邮件没有奖励
				return;
			}


			if ((reward.getType().getGroup().equals(CurrencyGroup.SOUL) && Soul.all(playerCode).size() >= Soul.maxNum)){
				send(messageSource, response, Result.MailNumMax);//邮件没有奖励
				return;
			}
		}

		new CurrencyHandle().addCurrency(playerCode, mailBean.getReason(), rewards);

		mailBean.setReaded(true);
		mailBean.setRewarded(true);
		MailBean.set(playerCode, mailBean);

		response.setMail(new MailHandle().packMail(playerCode, mailBean));
		response.addAllRewards(new CurrencyHandle().packItems(rewards));
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, MailMessage.MailReceivedResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}